<template>
  <div v-if="!loading" class="app-container">
    <el-table
      v-loading="loading"
      :data="dataList"
      row-key="indicatorName"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="编号" align="center" prop="id" width="100"/>
      <el-table-column label="指标名称" align="left" prop="indicatorName" :show-overflow-tooltip="true"/>
      <el-table-column
        label="得分"
        align="right"
        prop="indicatorValue"
        :formatter="formatScore"
        width="120"/>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getData"
    />
  </div>
</template>

<script>
import { listIndicatorEvaluationScoreByResult } from "@/api/evaluate/IndicatorEvaluationScore"
import { getIndicatorsTree } from "@/api/indicator/indicator"

export default {
  name: "Score",
  data() {
    return {
      loading: true,
      dataList: [],
      isExpandAll: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 格式化得分显示，保留2位小数
    formatScore(row, column, value) {
      return value != null ? parseFloat(value).toFixed(2) : '-'
    },

    // 获取指标数据
    async getData() {
      try {
        this.loading = true
        // 获取指标树结构
        const treeRes = await getIndicatorsTree()
        this.dataList = treeRes.rows
        this.total = treeRes.total

        // 获取指标得分数据
        const scoreRes = await listIndicatorEvaluationScoreByResult(this.$store.state.evaluate.id)
        console.log('得分数据:', scoreRes)
        this.updateIndicatorScores(scoreRes.data)
      } catch (error) {
        console.error('获取数据失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 更新指标得分
    updateIndicatorScores(scores) {
      const scoreMap = new Map(scores.map(item => [item.indicatorId, item.indicatorValue]))
      this.updateScoresRecursively(this.dataList, scoreMap)
    },

    // 递归更新得分
    updateScoresRecursively(nodes, scoreMap) {
      nodes.forEach(node => {
        if (scoreMap.has(node.id)) {
          this.$set(node, 'indicatorValue', scoreMap.get(node.id))
        }
        if (node.children) {
          this.updateScoresRecursively(node.children, scoreMap)
        }
      })
    }
  }
}
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
